package org.catpay.modules.app.service.impl;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang.StringUtils;
import org.catpay.common.exception.RRException;
import org.catpay.common.utils.PageUtils;
import org.catpay.common.utils.Query;
import org.catpay.modules.app.contants.SysConfig;
import org.catpay.modules.app.dao.IncomeDao;
import org.catpay.modules.app.entity.IncomeDataEntity;
import org.catpay.modules.app.entity.UserEntity;
import org.catpay.modules.app.entity.WithdrawalDataEntity;
import org.catpay.modules.app.service.AccService;
import org.catpay.modules.sys.service.SysConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;

@Service("accService")
public class AccountServiceImpl extends ServiceImpl<IncomeDao, IncomeDataEntity> implements AccService {

	@Autowired
	SysConfigService sysConfigService;

	@Override
	public List<IncomeDataEntity> getUserIncomeData(long userId, String start, String end, String pageNo,
			String pageSzie) {
		return baseMapper.getUserIncomeData(userId, start, end, Integer.valueOf(pageNo) * Integer.valueOf(pageSzie),
				Integer.valueOf(pageSzie));
	}

	@Override
	public BigDecimal getUserIncome(long userId, String starttime, String endtime) {
		return baseMapper.getUserIncome(userId, starttime, endtime);
	}

	@Override
	@Transactional
	public void withdraw(UserEntity user, String amount, String aliId, String name, String password) {

		// 查询是否提现审核中
		int count = baseMapper.queryWithdrawCount(user.getId());
		if (count > 0) {
			throw new RRException("有未处理提现");
		}

		String charge = sysConfigService.getValue(SysConfig.CHARGE);
		BigDecimal amountDec = new BigDecimal(amount).setScale(2, BigDecimal.ROUND_HALF_UP);
		BigDecimal chargeDec;
		if (StringUtils.isNotBlank(charge)) {
			chargeDec = new BigDecimal(charge).setScale(2, BigDecimal.ROUND_HALF_UP);
			if (chargeDec.compareTo(amountDec) == 1) {
				throw new RRException("提现金额小于手续费");
			}
		} else {
			chargeDec = new BigDecimal(0);
		}

		if ((user.getAccountBalance().subtract(user.getFrozenBalance())).compareTo(amountDec) == -1) {
			throw new RRException("提现金额大于账户可用余额");
		}

		WithdrawalDataEntity withdrawalDataEntity = new WithdrawalDataEntity();
		withdrawalDataEntity.setPhone(user.getPhone());
		withdrawalDataEntity.setUserId(user.getId());
		withdrawalDataEntity.setNickName(user.getNickName());
		// withdrawalDataEntity.setRemark();
		withdrawalDataEntity.setTransferId(aliId);
		withdrawalDataEntity.setToName(name);
		BigDecimal amountBig = new BigDecimal(amount).setScale(2, BigDecimal.ROUND_HALF_UP);
		withdrawalDataEntity.setAmount(amountBig);
		withdrawalDataEntity.setServicechargeAmount(chargeDec);
		withdrawalDataEntity.setCreateTime(new Date());
		withdrawalDataEntity.setStatus(1);
		// 记录提现
		baseMapper.withdraw(withdrawalDataEntity);

		// 更新冻结金额
		baseMapper.updateFrozenBalance(user.getId(), amountBig);
	}

	@Override
	public List<WithdrawalDataEntity> getWithdrawalData(long userId, String pageNo, String pageSzie) {
		return baseMapper.getWithdrawalData(userId, Integer.valueOf(pageNo) * Integer.valueOf(pageSzie),
				Integer.valueOf(pageSzie));
	}

	@Override
	public void withdrawResult(Long id, Integer status) {
		WithdrawalDataEntity withdrawalDataEntity = baseMapper.queryWithdraw(id);
		if (null == withdrawalDataEntity) {
			throw new RRException("不存在未处理提现");
		}
		// 更新提现记录状态
		baseMapper.withdrawResult(id, status);
		// 修改用户余额、冻结金额
		if (status == 2) {
			// 提现成功 修改余额
			baseMapper.updateAccountBalance(withdrawalDataEntity.getUserId(), withdrawalDataEntity.getAmount());
			// 清零冻结金额
			baseMapper.updateFrozenBalance(withdrawalDataEntity.getUserId(), new BigDecimal(0));
		} else if (status == 3) {
			// 提现失败 清零冻结金额
			baseMapper.updateFrozenBalance(withdrawalDataEntity.getUserId(), new BigDecimal(0));
		}
	}

	@Override
	public void addUserIncome(long userId, BigDecimal amount, String orderNo, String type, Long buyUserId, String rule,
			String remark) {
		UserEntity userEntity = baseMapper.queryUser(userId);
		IncomeDataEntity incomeDataEntity = new IncomeDataEntity();
		incomeDataEntity.setOrderNo(orderNo);
		incomeDataEntity.setPhone(userEntity.getPhone());
		incomeDataEntity.setUserId(userId);
		incomeDataEntity.setNickName(userEntity.getNickName());
		incomeDataEntity.setRule(rule);
		incomeDataEntity.setRemark(remark);
		incomeDataEntity.setBuyUserId(buyUserId);
		incomeDataEntity.setAmount(amount);
		incomeDataEntity.setCreateTime(new Date());
		incomeDataEntity.setType(type);
		baseMapper.insert(incomeDataEntity);
	}

	@Override
	public PageUtils queryUserIncomeDataPage(Map<String, Object> params) {
		String startTime = MapUtils.getString(params, "startTime");
		String endTime = MapUtils.getString(params, "endTime");
		Long userId = MapUtils.getLong(params, "userId");
		Page<IncomeDataEntity> page = this.selectPage(new Query<IncomeDataEntity>(params).getPage(),
				new EntityWrapper<IncomeDataEntity>().eq("user_id", userId).ge("create_time", startTime)
						.le("create_time", endTime));

		return new PageUtils(page);
	}

}
